import { createRouter, createWebHistory } from 'vue-router'
import routes from './routes'
import { websiteTitle } from '@/config'
import { useUserStore } from '@/stores'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
})

router.afterEach((to) => {
  const { title } = to.meta
  document.title = title ? `${title} - ${websiteTitle}` : websiteTitle
})
router.beforeEach((to) => {
  //判断该路由是否需要登录权限
  if (to.matched.some((record) => record.meta.requiresAuth)) {
    // 路由需要验证，判断用户是否已经登录
    const store = useUserStore()
    if (store.userInfo && store.userInfo.username) {
      return true
    } else {
      return {
        path: '/login',
        query: {
          redirect: to.fullPath,
        },
      }
    }
  } else return true
})
export default router
